import { ref, type Ref } from "vue";
import { defineStore } from "pinia";

import { authApi } from "@/api/auth";
import { resetRouter } from "@/router";
import { store } from "@/stores";
import { useRoute, useRouter } from "vue-router";
import { storageUtil } from "@/utils/storage";

import type { LoginData, UserInfo, RolesPerms } from "@/api/auth/types";
import type { LoginUserInfo, LoginUserToken } from "@/api/sys/types";
import type { LoginResponse } from "@/api/wechat/types";
import type { AlipayRegisterData, AlipayLoginData, AlipayLoginResponse } from "@/api/alipay/types";
import type {
  UnionPayLoginData,
  UnionPayRegisterData,
  UnionPayLoginResponse
} from "@/api/unionpay/types";
import { showLoadingToast, closeToast } from "vant";
import { wechatApi } from "@/api/wechat";
import { alipayApi } from "@/api/alipay/index";
import { unionPayApi } from "@/api/unionpay/index";
import { type LoginResult } from "@/api/auth/types";
import { useStorage } from "@vueuse/core";

export const useUserStore: any = defineStore("user", () => {
  const user: Ref<LoginUserInfo> = ref({
    tenant: "", // 租户
    roleCodes: [],
    permCodes: []
  });

  const token = useStorage("accessToken", "");
  const userToken = useStorage<LoginUserToken>("userToken", {});

  // 存储token
  const setToken = (data: LoginResult) => {
    const { accessToken } = data;
    token.value = accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
    data.expiresDate = new Date().getTime() + data.expiresIn * 1000;
    data.tenant = user.value.tenant;
    userToken.value = data;
  };
  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      authApi
        .login(loginData)
        .then((response: any) => {
          setToken(response.data);
          resolve();
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    });
  }

  // 登录
  function wechatLogin(requestId: string): Promise<LoginResponse> {
    return new Promise<LoginResponse>((resolve, reject) => {
      // showLoadingToast({ message: "登录中...", forbidClick: true });
      const route = useRoute();
      const router = useRouter();
      const data = wechatApi.createLoginData(route, "/wechat/register");
      data.requestId = requestId;
      wechatApi
        .login(data)
        .then((res) => {
          if (res.data.status) {
            setToken(res.data.token);
            const redirect = storageUtil.getRedirect();
            console.log("redirect json:" + redirect);
            storageUtil.removeRedirect();
            router.push(redirect);
            closeToast();
            return;
          }
          resolve(res.data);
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    });
  }

  // 注册
  function wechatRegister(requestId: string) {
    const route = useRoute();
    const router = useRouter();
    const registerData = wechatApi.createLoginData(route);
    registerData.requestId = requestId;
    wechatApi.register(registerData).then((res) => {
      if (res.data.status) {
        setToken(res.data.token);
        getUserInfo();
        const redirect = storageUtil.getRedirect();
        console.log("redirect json:" + redirect);
        storageUtil.removeRedirect();
        router.push(redirect);
        closeToast();
        return;
      }
    });
  }

  /** 阿里静默登录. */
  function alipayLogin(loginData: AlipayLoginData): Promise<AlipayLoginResponse> {
    return new Promise<AlipayLoginResponse>((resolve, reject) => {
      alipayApi
        .login(loginData)
        .then((response) => {
          if (response.data.status) {
            setToken(response.data.token);
          }
          resolve(response.data);
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    });
  }

  /** 阿里注册登录. */
  function alipayRegister(loginData: AlipayRegisterData): Promise<AlipayLoginResponse> {
    return new Promise<AlipayLoginResponse>((resolve, reject) => {
      alipayApi
        .register(loginData)
        .then((response) => {
          if (response.data.status) {
            setToken(response.data.token);
          }
          resolve(response.data);
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    });
  }

  /** 云闪付静默登录. */
  function unionpayLogin(loginData: UnionPayLoginData): Promise<UnionPayLoginResponse> {
    return new Promise<UnionPayLoginResponse>((resolve, reject) => {
      unionPayApi
        .login(loginData)
        .then((response) => {
          if (response.data.status) {
            setToken(response.data.token);
          }
          resolve(response.data);
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    });
  }

  /** 云闪付注册登录. */
  function unionpayRegister(loginData: UnionPayRegisterData): Promise<UnionPayLoginResponse> {
    return new Promise<UnionPayLoginResponse>((resolve, reject) => {
      unionPayApi
        .register(loginData)
        .then((response) => {
          if (response.data.status) {
            setToken(response.data.token);
          }
          resolve(response.data);
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    });
  }

  //是否Token过期.
  function isTokenExpires(): boolean {
    //租户不一致视为过期
    if (userToken.value && userToken.value.tenant && user.value.tenant != userToken.value.tenant) {
      console.log("当前租户:", user.value.tenant);
      console.log("Token租户：", userToken.value.tenant);
      //清理Token.
      clearToken();
      return true;
    }
    if (userToken.value && userToken.value["expiresDate"]) {
      const now = new Date().getTime();
      //提前1分钟过期.
      return now + 60000 > userToken.value["expiresDate"];
    }
    return false;
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      authApi
        .userInfo()
        .then(({ data }) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          Object.assign(user.value, { ...data });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取角色权限
  function getRoleInfo(): Promise<RolesPerms> {
    return new Promise<RolesPerms>((resolve, reject) => {
      authApi
        .userRolesPerms()
        .then(({ data }) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          Object.assign(user.value, { ...data });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 刷新Token
  function refreshToken(tokenParam: string) {
    return new Promise<string>((resolve, reject) => {
      authApi
        .refreshToken(tokenParam)
        .then((response: any) => {
          const { accessToken } = response.data;
          token.value = accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          response.data["expiresDate"] = new Date().getTime() + response.data["expiresIn"] * 1000;
          userToken.value = response.data;
          resolve(token.value);
        })
        .catch((error) => {
          token.value = "";
          userToken.value = {};
          console.log(error);
          reject(error);
        });
    });
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      authApi
        .logout(token.value)
        .then(() => {
          token.value = "";
          user.value.roleCodes = [];
          user.value.permCodes = [];
          userToken.value = {};
          // location.reload(); // 清空路由
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // remove token
  function resetToken() {
    return new Promise<void>((resolve) => {
      token.value = "";
      userToken.value = {};
      resetRouter();
      resolve();
    });
  }

  // clear token
  function clearToken() {
    return new Promise<void>((resolve) => {
      token.value = "";
      userToken.value = {};
      resolve();
    });
  }

  return {
    token,
    user,
    userToken,
    login,
    wechatLogin,
    wechatRegister,
    alipayLogin,
    alipayRegister,
    unionpayLogin,
    unionpayRegister,
    getUserInfo,
    logout,
    resetToken,
    clearToken,
    isTokenExpires,
    refreshToken,
    getRoleInfo
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
